const path = require('path');
const fs = require('fs');

const regStyle = /<style>[\s\S]*<\/style>/;
const refScript = /<script>[\s\S]*<\/script>/;


fs.readFile(path.join(__dirname, '/index.html'), 'utf-8', (error, data) => {
    if (error != null) {
        return console.log('读取文件失败，错误信息为：' + error.message);
    } else {
        resolveCSS(data);
        resolveJS(data);
        resolveHtml(data);
    }

});



function resolveCSS(htmlStr) {
    var r1 = regStyle.exec(htmlStr);
    var newCss = r1[0].replace('<style>', '').replace('</style>', '');
    fs.writeFile(path.join(__dirname, '/clock/index.css'), newCss, function(error) {
        if (error) {
            console.log('写文件出现错误，错误信息为：', error.message);
        } else {
            console.log('写文件成功');
        }
    })
}

function resolveJS(htmlStr) {
    var r2 = refScript.exec(htmlStr);
    var newJs = r2[0].replace('<script>', '').replace('</script>', '');
    fs.writeFile(path.join(__dirname, '/clock/index.js'), newJs, error => {
        if (error) {
            console.log('写文件出现错误，错误信息为：', error.message);
        } else {
            console.log('写文件成功');
        }
    })
}

function resolveHtml(htmlStr) {
    var r1 = regStyle.exec(htmlStr);
    var r2 = refScript.exec(htmlStr);
    htmlStr = htmlStr.replace(r1, '<link rel="stylesheet" href="./index.css" />')
        .replace(r2, ' <script src="./index.js"></script>');
    fs.writeFile(path.join(__dirname, '/clock/index.html'), htmlStr, error => {
        if (error) {
            console.log('写文件出现错误，错误信息为：', error.message);
        } else {
            console.log('写文件成功');
        }
    });
}